package com.beiding.dbrequest.common;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.java.Log;

/**
 * 处理器公共行为
 */
@Log
public class HandlerCommon {

    /**
     * 消息类型处理器枚举,以避免使用if-else分支判断
     */
    private static DoHandle[] handles = new DoHandle[4];

    static {

        //定义四种类型的处理策略

        handles[Message.TYPE_HEARTBEAT] = (ctx, msg, dispatcher, requestTable) -> {
            //无操作
        };
        handles[Message.TYPE_REQUEST] = (ctx, msg, dispatcher, requestTable) -> {
            //分发数据
            dispatcher.onMessage(ctx, msg);
        };
        handles[Message.TYPE_RESPONSE] = (ctx, msg, dispatcher, requestTable) -> {
            //分发响应
            requestTable.onResponse(msg);
        };
        handles[Message.TYPE_BROADCAST] = (ctx, msg, dispatcher, requestTable) -> {
            //有请求但是忽略结果
            dispatcher.onMessageIgnoreResult(ctx, msg);
        };
    }

    /**
     * 当消息产生时处理逻辑
     * @param ctx
     * @param msg
     * @param dispatcher
     * @param requestTable
     * @throws Exception
     */
    public static void onMessage(ChannelHandlerContext ctx, Message msg, Dispatcher dispatcher, RequestTable requestTable) throws Exception {
        handles[msg.getType()].onMessage(ctx, msg, dispatcher, requestTable);
    }

    private interface DoHandle {
        /**
         * 消息处理行为定义
         * @param ctx
         * @param msg
         * @param dispatcher
         * @param requestTable
         * @throws Exception
         */
        void onMessage(ChannelHandlerContext ctx, Message msg, Dispatcher dispatcher, RequestTable requestTable) throws Exception;
    }

}
